#!/bin/bash

# 目标目录
target_dir="/mnt/workspace/cuda/cuda-samples/Samples"
# 结果记录文件
log_file="$target_dir/execution_results.log"

# 创建日志文件所在的目录（如果已存在不会报错）
mkdir -p $(dirname "$log_file")

# 清空日志文件内容（可选操作，若不需要每次清空可去掉此行）
> "$log_file"

# 遍历一级子目录
for first_level_dir in "$target_dir"/*; do
    if [ -d "$first_level_dir" ]; then
        # 遍历二级子目录
        for second_level_dir in "$first_level_dir"/*; do
            if [ -d "$second_level_dir" ]; then
                # 判断是否为需要跳过的目录
                skip_dirs=(
                    "matrixMulCUBLAS"
                    "simpleAttributes"
                    "libNVVM"
                    "MC_EstimatePiInlineQ"
                    "MC_EstimatePiQ"
                    "MersenneTwisterGP11213"
                    "batchCUBLAS"
                    "graphMemoryNodes"
                    "matrixMulDynlinkJIT"
                    "memMapIPCDrv"
                    "simpleCUBLAS"
                    "simpleCUBLASXT"
                    "simpleCUBLAS_LU"
                    "systemWideAtomics"
                    "streamOrderedAllocationIPC"
                )
                is_skip=false
                for skip_dir in "${skip_dirs[@]}"; do
                    if [[ "$second_level_dir" == *"/$skip_dir" ]]; then
                        is_skip=true
                        break
                    fi
                done
                if [ "$is_skip" = true ]; then
                    echo "跳过目录: $second_level_dir"
                    echo "Skipping directory: $second_level_dir" >> "$log_file"
                    continue
                fi

                # 进入第二级子目录
                cd "$second_level_dir" || continue
                echo "--------------开始执行 $second_level_dir -------------"
                echo "--------------开始执行 $second_level_dir -------------" >> $log_file
                echo "正在处理目录: $second_level_dir"
                echo "正在处理目录: $second_level_dir" >> $log_file

                # 尝试进行编译，使用make进行编译
                make >> $log_file 2>&1
                if [ $? -eq 0 ]; then
                    # 如果编译成功，执行生成的可执行文件，假设可执行文件名为可执行文件在当前目录下的主文件名
                    result=$("./$(basename "$second_level_dir")" 2>&1)
                    echo "执行结果: "
                    echo "执行结果: " >> $log_file
                    echo "$result"
                    echo "$result" >> $log_file
                    echo "--------------执行结束-------------"
                    echo "--------------执行结束-------------" >> $log_file
                    echo " "
                    echo " " >> "$log_file"
                else
                    echo "编译 $second_level_dir 失败，执行结束，详细错误信息查看日志文件----------"
                    echo "编译 $second_level_dir 失败，执行结束，详细错误信息查看日志文件----------" >> "$log_file"
                    echo " "
                    echo " " >> "$log_file"
                fi

                # 返回上级目录
                cd - > /dev/null
            fi
        done
    fi
done